#include <iostream>
using namespace std;

// Definition for singly-linked list.
struct ListNode {
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        // 创建一个头节点
        ListNode dummy(0, head);
        auto cur = &dummy;
        // 当头节点的下一个节点和下下一个节点不是空的时候循环就继续下去
        while (cur->next && cur->next->next)
        {
            int val = cur->next->val;
            // 如果后两个节点的值相同
            if (cur->next->next->val == val)
            {
                // 值等于val的节点全部删除
                while (cur->next && cur->next->val == val)
                {
                    cur->next = cur->next->next;
                }
                
            }else{
                cur = cur->next;
            }
            
        }
        return dummy.next;
    }
};

// 工具函数：创建链表
ListNode* createList(int arr[], int n) {
    if (n == 0) return nullptr;
    ListNode* head = new ListNode(arr[0]);
    ListNode* cur = head;
    for (int i = 1; i < n; ++i) {
        cur->next = new ListNode(arr[i]);
        cur = cur->next;
    }
    return head;
}

// 工具函数：打印链表
void printList(ListNode* head) {
    while (head) {
        cout << head->val;
        if (head->next) cout << " -> ";
        head = head->next;
    }
    cout << endl;
}

int main()
{
    // 测试用例数组
    int test1[] = {1, 2, 2, 3, 4, 4, 5};
    int test2[] = {2, 2, 2};
    int test3[] = {1, 1, 2, 3};
    int test4[] = {1, 2, 3, 4};
    int test5[] = {1, 1, 2, 2, 3, 3};

    // 运行测试用例
    Solution sol;

    cout << "Test Case 1:" << endl;
    ListNode* head1 = createList(test1, sizeof(test1)/sizeof(test1[0]));
    cout << "Input: ";
    printList(head1);
    ListNode* res1 = sol.deleteDuplicates(head1);
    cout << "Output: ";
    printList(res1);

    cout << "Test Case 2:" << endl;
    ListNode* head2 = createList(test2, sizeof(test2)/sizeof(test2[0]));
    cout << "Input: ";
    printList(head2);
    ListNode* res2 = sol.deleteDuplicates(head2);
    cout << "Output: ";
    printList(res2);

    cout << "Test Case 3:" << endl;
    ListNode* head3 = createList(test3, sizeof(test3)/sizeof(test3[0]));
    cout << "Input: ";
    printList(head3);
    ListNode* res3 = sol.deleteDuplicates(head3);
    cout << "Output: ";
    printList(res3);

    cout << "Test Case 4:" << endl;
    ListNode* head4 = createList(test4, sizeof(test4)/sizeof(test4[0]));
    cout << "Input: ";
    printList(head4);
    ListNode* res4 = sol.deleteDuplicates(head4);
    cout << "Output: ";
    printList(res4);

    cout << "Test Case 5:" << endl;
    ListNode* head5 = createList(test5, sizeof(test5)/sizeof(test5[0]));
    cout << "Input: ";
    printList(head5);
    ListNode* res5 = sol.deleteDuplicates(head5);
    cout << "Output: ";
    printList(res5);

    return 0;
}